<?php

App::uses('AppModel', 'Model');
App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationGroup Model
 *
 * @property OrganisationGroupType $OrganisationGroupType
 * @property OrganisationMemberGroup $OrganisationMemberGroup
 */
class OrganisationRole extends CompositeKeyModel {

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * hasMany associations
     *
     * @var array
     */
    public $hasMany = array(
        'OrganisationAccount' => array(
            'className' => 'OrganisationAccount',
            'foreignKey' => 'organisation_role_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'OrganisationRoleModule' => array(
            'className' => 'OrganisationRoleModule',
            'foreignKey' => 'organisation_role_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );
    
    public $hasAndBelongsToMany = array(
        'Module' => array(
            'className' => 'Module',
            'joinTable' => 'organisation_role_modules',
            'foreignKey' => 'organisation_role_id',
            'associationForeignKey' => 'module_id',
            'unique' => true,
            'conditions' => 'Module.active = 1',
            'dependent' => false
        )
    );

    public function createDefault($organisation_id, $member_account_id) {
        $roles = array(
            'OrganisationRole' => array(
                'organisation_id' => $organisation_id,
                'name' => 'Administrator',
                'description' => 'Overall administrator with all account privileges',
                'admin_access' => 1
            ),
            'OrganisationAccount' => array(
                array(
                    'organisation_id' => $organisation_id,
                    'member_account_id' => $member_account_id,
                    'name' => 'Administrator',
                    'description' => 'Default administrator account for this organisation'
                )
            )
        );
        
        $this->saveAll($roles);

        $role_data = $this->find('first',array(
            'contain' => array('OrganisationAccount'),
            'conditions' => array('organisation_id' => $organisation_id)
        ));
        
        $org_modules = ClassRegistry::init('OrganisationModule')->find('all', array(
            'contain' => array(
                'Module' => array(
                    'ModuleMenu' => array(
                        'fields' => array('id')
                    )
                )
            ),
            'conditions' => array(
                'OrganisationModule.organisation_id' => $organisation_id
            )
        ));
        
        $role_module_data = array();
        
        foreach($org_modules as $module) {
            $menu_ids = array();
            
            foreach($module['Module']['ModuleMenu'] as $menu) {
                $menu_ids[] = $menu['id'];
            }
            
            $role_module_data[] = array(
                'OrganisationRoleModule' => array(
                    'organisation_role_id' => $role_data['OrganisationRole']['id'],
                    'module_id' => $module['Module']['id'],
                    'module_menu_ids' => implode(",", $menu_ids)
                )
            );
        }
        
        // create the role modules
        $this->OrganisationRoleModule->saveAll($role_module_data);
        
        return array('organisation_role_id' => $role_data['OrganisationRole']['id'], 'organisation_account_id' => $role_data['OrganisationAccount'][0]['id']);
    }
    
    /**
     * Creates or updates a role record with the supplied data
     * 
     * @param array $data
     * @return array
     */
    public function updateRole($data) {
        $save = array(
            'OrganisationRole' => array(
                'id' => isset($data['role_id']) && !empty($data['role_id']) ? $data['role_id'] : null,
                'organisation_id' => $data['organisation_id'],
                'name' => $data['role_name'],
                'admin_access' => isset($data['admin_access']) ? 1 : 0
            ),
            'OrganisationRoleModule' => array()
        );
        
        foreach($data['module'] as $module) {
            if( isset($module['module_id']) ) {
                $save['OrganisationRoleModule'][] = array(
                    'id' => isset($module['id']) && !empty($module['id']) ? $module['id'] : null,
                    'organisation_role_id' => isset($module['role_id']) && !empty($module['role_id']) ? $module['role_id'] : null,
                    'module_id' => $module['module_id'],
                    'module_menu_ids' => isset($module['module_menu_ids']) ? implode(",", $module['module_menu_ids']) : '',
                    'active' => 1
                );
            }
            
            else if( isset($module['id']) ) {
                $save['OrganisationRoleModule'][] = array(
                    'id' => $module['id'],
                    'active' => 0
                );
            }
        }
        
        $saved = $this->saveAll($save, array('deep' => true, 'atomic' => true));
        
        if( $saved ) {
            return array('status' => 'success', 'message' => 'Role saved successfully', 'role_id' => $this->id, 'data' => $save);
        }
        
        else {
            return array('status' => 'failed', 'message' => 'Role save process failed. Please check data and try again');
        }
    }
    
    /**
     * Flags a role record as deleted
     * 
     * @param int $organisation_id
     * @param int $role_id
     */
    public function markDeleted($organisation_id, $role_id) {
        $this->updateAll(array(
            'OrganisationRole.active' => 0
        ),array(
            'OrganisationRole.organisation_id' => $organisation_id,
            'OrganisationRole.id' => $role_id
        ));
        
        return array('status' => 'success', 'message' => 'Roles flagged deleted successfully');
    }
}
